package com.supermap.application.controller;

import com.alibaba.fastjson.JSONObject;
import com.supermap.application.common.IndexInfoVO;
import com.supermap.application.common.OpStatus;
import com.supermap.application.entity.*;
import com.supermap.application.service.DepartmentService;
import com.supermap.application.service.MacroTablemetaService;
import com.supermap.application.service.TargetManageService;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.annotation.Target;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 目标管理视图；禁止写业务代码
 */
@Controller
@RequestMapping(value = "/target")
public class TargetManageController {

    @Autowired
    TargetManageService targetManageService;

    @Autowired
    MacroTablemetaService macroTablemetaService;

    @Autowired
    DepartmentService departmentService;

    /**
     * 首页版权信息
     * @return
     */
    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(){
        return targetManageService.test();
    }

    /**
     * 获取指标体系信息
     * @return
     */
    @RequestMapping(value = "/getComboBox")
    @ResponseBody
    public List getComboBox(String year){
        List allIndexSys = this.targetManageService.findAllIndexSys(year);
        return allIndexSys;
    }

    /**
     * 根据目标体系名称获取所含的指标类型
     * @param name
     * @return
     */
    @RequestMapping(value = "/getComboBox/getIndexType")
    @ResponseBody
    public List getIndexType(String name){
        List indexSysTypeByName = this.targetManageService.findIndexSysTypeByName(name);
        return indexSysTypeByName;
    }


    /**
     * 根据指标分类id获取指标树
     * @param id 分类指标主键
     * @return
     */
    @RequestMapping("/getIndexTreeData")
    @ResponseBody
    public List getIndexTreeData(String id){
        List indexSysTypeColByName = this.targetManageService.findIndexSysTypeColByName(id);
        return indexSysTypeColByName;
    }

    /**
     * 获取部门信息
     * 根据部门表获取
     * @return
     */
    @RequestMapping("/getDep")
    @ResponseBody
    public Map getDepData(String year, String code){
        Map allDep = this.targetManageService.findAllDep(year,code);
        System.out.println(allDep.get("result").toString());
        return allDep;
    }


    /**
     * 获取单个指标对应数据
     * @param id  单个指标的主键
     * @param time
     * @param diquName
     * @param code
     * @return
     */
    @RequestMapping("/getIndexData")
    @ResponseBody
    public Map getIndexData(String id, String time, String diquName, String code){
        String year = time.substring(0,4);
        String tablename = "T_ECO_" + code + "_" + year;
        Map indexDataByIndexName = this.targetManageService.findIndexDataByIndexName(id,time,diquName,tablename);
        System.out.println(indexDataByIndexName);
        return indexDataByIndexName;
    }

    /**
     * 单个指标对应所有数据
     * @param id 指标主键
     * @param diquName 部门名称
     * @param year 指标体系年份
     * @param code 指标体系code
     * @return
     */
    @RequestMapping("/getIndexData/allseason")
    @ResponseBody
    public Map getAllSeasonIndexData(String id, String diquName, String year, String code){
        String tablename = "T_ECO_" + code + "_" + year;
        Map indexDataByIndexName = this.targetManageService.findIndexAllSeasonDataByIndexName(id,diquName,tablename,year);
        System.out.println(indexDataByIndexName);
        return indexDataByIndexName;
    }

    /**
     * 根据部门名称查询指标数据
     * @param depName
     * @return
     */
    @RequestMapping("/getIndexData/byDep")
    @ResponseBody
    public Map getIndexDataByDep(String depName){
        Map dataGroupByDep = this.targetManageService.findDataGroupByDep(depName);
        return dataGroupByDep;
    }


    //指标体系子模块
    /**
     * 指标体系---增加一个指标体系
     * @param indexSys
     * @return
     */
    @RequestMapping(value = "/add/indexSys", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus addTargetSys(TIndexSys indexSys){
        boolean indexSys1 = this.targetManageService.createIndexSys(indexSys);
        return new OpStatus(indexSys1, indexSys1 ? "添加成功" : "目标体系已存在，添加失败",null );
    }

    /**
     * 指标体系---查询一个指标体系信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/find/one", method = RequestMethod.GET)
    @ResponseBody
    public TIndexSys findIndexSysOnde(String id){
        return this.targetManageService.findById(id);
    }

    /**
     * 指标体系---更新指标体系
     * @param indexSys
     * @return
     */
    @RequestMapping(value = "/update/indexSys", method = RequestMethod.POST)
    @ResponseBody
    public TIndexSys updateIndexSys(TIndexSys indexSys){
        TIndexSys b = this.targetManageService.updateIndexSy(indexSys);
        return b;
    }

    /**
     * 指标体系---删除指标体系
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/indexSys", method = RequestMethod.GET)
    @ResponseBody
    public OpStatus deleteIndexSys(String id){
        boolean b = this.targetManageService.deleteIndexSys(id);
        return new OpStatus(b, b ? "删除成功" : "删除失败", null);
    }
    //指标体系子模块



    //分类指标功能
    /**
     * 分类指标---添加指标分类
     * @param tIndexSysType
     * @return
     */
    @RequestMapping(value = "/add/indexType", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus addIndexType(TIndexSysType tIndexSysType){
        boolean b = this.targetManageService.addIndexSysType(tIndexSysType);
        return new OpStatus(b, b ? "添加成功！" : "分类已存在，添加失败！", null);
    }

    /**
     * 分类指标---更新指标类型
     * @param tIndexSysType
     * @return
     */
    @RequestMapping(value = "/update/indexType", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus updateIndexType(TIndexSysType tIndexSysType){
        TIndexSysType tIndexSysType1 = this.targetManageService.updateIndexType(tIndexSysType);
        if (tIndexSysType1 != null){
            return new OpStatus(true,"修改成功！",null);
        }else {
            return new OpStatus(false,"修改失败！",null);
        }
    }


    /**
     * 分类指标---查询所有分类指标
     * @return
     */
    @RequestMapping(value = "/find/indexType", method = RequestMethod.GET)
    @ResponseBody
    public List<TIndexSysType> findAllIndexType(String sysCode){
        return this.targetManageService.findAllIndexType(sysCode);
    }


    /**
     * 分类指标---删除一个分类指标
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/indexType", method = RequestMethod.GET)
    @ResponseBody
    public OpStatus deleteIndexType(@RequestParam String id){
        boolean b = this.targetManageService.deleteIndexType(id);
        return new OpStatus(b, b ? "删除成功！" : "删除失败！", null);
    }
    //分类指标功能



    //指标维护功能
    /**
     *指标维护---查询所有可关联指标
     */
    @RequestMapping(value = "/find/tableMetas")
    @ResponseBody
    public List<TMacroTablemeta> findAllTablemeta(){
        List<TMacroTablemeta> allTablemetas = this.macroTablemetaService.findALLTablemetas();
        return allTablemetas;
    }


    /**
     * 指标维护---获取目标体系下所有指标
     * @param id 指标体系主键
     * @return
     */
    @RequestMapping(value = "/findCol/bySysId")
    @ResponseBody
    public List findAllSysTypeCol(String id){
        return this.targetManageService.findAllSysIndexCol(id);
    }


    /**
     *指标维护---获取一个指标信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/find/indexCod/one")
    @ResponseBody
    public JSONObject getOne(String id){
        JSONObject sysTypeColOne = this.targetManageService.findSysTypeColOne(id);
        return sysTypeColOne;
    }


    /**
     * 指标维护---添加指标 indexSysCol pid存在则是添加子节点 不存在添加根节点
     * @param tIndexSysTypeCol
     * @return
     */
    @RequestMapping(value = "/addOrUpdate/indexCol", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus addOrUpdateIndexCol(TIndexSysTypeCol tIndexSysTypeCol){
        boolean b = this.targetManageService.addOrUpdateIndexCol(tIndexSysTypeCol);
        return new OpStatus(b, b ? "操作成功！" : "操作失败！", null);
    }

    /**
     * 更新一个指标
     * @param tIndexSysTypeCol
     * @return
     */
    @RequestMapping(value = "/update/indexCol", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus updateIndexCol(TIndexSysTypeCol tIndexSysTypeCol){
        boolean b = this.targetManageService.updateIndexCol(tIndexSysTypeCol);
        return new OpStatus(b, b ? "修改成功！" : "修改失败！",null);
    }


    /**
     * 查询所有部门
     * @return
     */
    @RequestMapping(value = "/find/departments")
    @ResponseBody
    public List<TDepartment> findAllDepartment(){
        return this.departmentService.findALLDepartment();
    }


    /**
     * 指标维护---删除指标
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/indexCol", method = RequestMethod.GET)
    @ResponseBody
    public OpStatus deleteIndexCol(String id){
        boolean b = this.targetManageService.deleteIndexCol(id);
        return new OpStatus(b, b ? "删除成功！" : "请先删除子节点！", null);
    }
    //指标维护功能



    //指标导入功能


    /**
     * 查询可用的年份
     * @return
     */
    @RequestMapping(value = "/find/years")
    @ResponseBody
    public JSONObject findYears(){
        return this.targetManageService.findYears();
    }


    /**
     * 查询一个目标体系下所有指标（非树形）
     * @param sysId
     * @return
     */
    @RequestMapping(value = "/all/indexCol/by/sysCode")
    @ResponseBody
    public List<TIndexSysTypeCol> findAllIndexCol(String sysId){
        return this.targetManageService.findAllBySysCode(sysId);
    }



    /**
     * excel模板下载
     * @param datas
     * @return
     */
    @RequestMapping(value = "/excel/download", method = RequestMethod.POST)
    @ResponseBody
    public void downLoadExcel(@RequestBody IndexInfoVO datas, HttpServletRequest request, HttpServletResponse response){
        System.out.println(datas);
        File workbook = this.targetManageService.downLoadExcel(datas);
        //File downLoadFile = new File(workbook);
        //OutputStream out = null;
        String fileName = null;
        HSSFWorkbook wb = null;
        try {

            InputStream inputStream = new FileInputStream(workbook);
            wb = new HSSFWorkbook(inputStream);
            OutputStream outputStream = response.getOutputStream();
            //response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8"); //设置下载内容信息03版Excel
            response.setCharacterEncoding("utf-8");
            //response.setLocale(Locale.CHINESE);
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")){
                fileName = URLEncoder.encode(workbook.getName(),"UTF-8");
            }else {
                fileName = new String(workbook.getName().getBytes("UTF-8"),"ISO-8859-1");
            }
            //fileName = URLDecoder.decode(fileName, "UTF-8");
            fileName = URLEncoder.encode(fileName,"UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename"+fileName);
            //response.setContentType("APPLICATION/vnd.ms-excel");

            wb.write(outputStream);
            //outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return new OpStatus(true,"下载成功！",null);
    }

    /**
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "/downFile")
    @ResponseBody
    public void downFile(HttpServletResponse response, HttpServletRequest request){
        String fileName = null;

        try {
            File file = TargetManageService.getFile();
            InputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();
            String userAgent = request.getHeader("User-Agent");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")){
                fileName = URLEncoder.encode(file.getName(),"UTF-8");
            }else {
                fileName = new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     * @param multipartFile  上传的文件
     * @param year 上传的报告期
     * @param code  目标体系编码
     * @param flag  是否重新导入  yes-重新导入 其他-在后面追加
     * @return
     */
    @RequestMapping(value = "/excel/upload")
    @ResponseBody
    public OpStatus uploadExcel(@RequestParam("file") MultipartFile multipartFile, String year, String code, String flag){
        Map<String, Object> map = this.targetManageService.uploadExcelToDatabase(multipartFile, year, code, flag);
        return new OpStatus(true, (String) map.get("result"),null );
    }
}
